// 检查定位界面按钮状态
function checkState() {
	// var devices = localStorage.getItem("devices");
	// if(devices != null) {
	//     var device = localStorage.getItem("device");
	//     if (device != null) {
	//         var imei = device.split(",")[0];
	//         // 检查定位按钮状态
	//         var locStart = localStorage.getItem(imei + "_loc_start");
	//         var locDuration = localStorage.getItem(imei + "_loc_duration");
	//         var locReport = localStorage.getItem(imei + "_loc_report");
	//         if(locStart != null) {
	//             locStart = parseInt(locStart);
	//             locDuration = locDuration == null ? 0 : parseInt(locDuration);
	//             if(new Date().getTime() - locStart > locDuration || (locReport != null && parseInt(locReport) > locStart)) {
	//                 document.getElementById("locLoading").style.display = "none";
	//             } else {
	//                 document.getElementById("locLoading").style.marginTop = "-174px";
	//                 document.getElementById("locLoading").style.display = "block";
	//             }
	//         }
	//         // 检查跟踪按钮状态
	//         var folStart = localStorage.getItem(imei + "_fol_start");
	//         var folDuration = localStorage.getItem(imei + "_fol_duration");
	//         if(folStart != null) {
	//             folStart = parseInt(folStart);
	//             var interval = parseInt(folDuration) * 1000;
	//             if(new Date().getTime() - folStart > interval) {
	//                 if(!(document.getElementById("locLoading").style.marginTop == "-174px" && document.getElementById("locLoading").style.display == "block"))
	//                     document.getElementById("locLoading").style.display = "none";
	//             } else {
	//                 document.getElementById("locLoading").style.marginTop = "-48px";
	//                 document.getElementById("locLoading").style.display = "block";
	//             }
	//         }
	//     }
	// }
}

function  div_loc_showloading(imei){
	  //是否是单次定位还是30分跟踪
  var model = Device.getCurrentModel();
    var msgType = Device.getMsgType(model);
    var linkType = Device.getLinkType(model);

    switch (msgType + linkType) {
		// 如果是收费的短信网关，并且是短链接，点击后，要提示客户：“开启30分钟的位置上报”，开启后，30分钟内不允许再次点击
			case '00': {
			var start= Device.getDeviceLocTime(imei);
			if(parseInt(new Date().getTime() - start)>= 1800 * 1000){
			
			Device.locationControl.data.showloading = false;
			}else{
			Device.locationControl.data.showloading = true;
			}
			break;
			}//case '10':
			case '10':
			case '11':
			case '01': {
			var start= Device.getDeviceLocTime(imei);
			if(parseInt(new Date().getTime() - start)>= 90 * 1000){
			Device.locationControl.data.showloading = false;
			}else{
			Device.locationControl.data.showloading = true;
			}
			break;
			}
			default: {
			var start= Device.getDeviceLocTime(imei);
			if(parseInt(new Date().getTime() - start)>= 90 * 1000){
			Device.locationControl.data.showloading = false;
			}else{
			Device.locationControl.data.showloading = true;
			}
			break;
			}

}
	
	
}
/*function  localStorage_createWindow(device){
	 Device.createMap();
	var imei=device[0];
	console.log(imei);
	var devices_bat  =device[3];
	var devices_lng  =device[4];
	var devices_lat =device[5];
	var devices_addr =device[6];
	var devices_created=device[10];
	if(map !=undefined){
		 map.clearOverlays();
		// 显示位置点
	        var point = new BMap.Point(devices_lng, devices_lat);
	        map.centerAndZoom(point, 16);
	}
	if (infoWindow) {
        infoWindow.close();
    }
        console.log(devices_bat+","+devices_lng+","+devices_lat+","+devices_addr+","+devices_created)
     //  window.setTimeout(function(){ map.panTo(point); }, 500);
         console.log("createWindow3");
createWindow(devices_addr, devices_lng, devices_lat, devices_created, devices_bat);
console.log("UGetGPS其它错误");

}*/


function localStorage_GPS(device){
    
    var point;
	
	var imei=device[0];
	console.log(imei);
	var devices_bat  =device[3];
	var devices_lng  =device[4];
	var devices_lat =device[5];
	var devices_addr =device[6];
	var devices_created=device[10];
	var devices_loctype=device[12];
    
        
  
    Device.createMap();
    map3.clearOverlays();
    if(devices_lng== 0&&devices_lat== 0){
    	var lng1=Math.round(31.0417850000 * 1000000) / 1000000;
        var lat1=Math.round(112.2058430000 * 1000000) / 1000000;
        var point=new BMap.Point(lat1,lng1);
            setTimeout(function(){map3.centerAndZoom(point,16)},100);
    }else{
    // 显示位置点
    point = new BMap.Point(devices_lng, devices_lat);
    console.log("localStorage_GPS-point-1:"+devices_lng+","+devices_lat);
    setTimeout(function(){map3.centerAndZoom(point,16)},100);
    

  
    var marker;
    if (devices_loctype == 1)
        marker = new BMap.Marker(point, {
            icon : new BMap.Icon("http://www.mingyitech.cn/mingyi/images/gps.png", new BMap.Size(36, 36), {
                                 anchor:new BMap.Size(18, 36),
                infoWindowAnchor : new BMap.Size(10, 0)
            })
        });
    else if (devices_loctype == 4)
        marker = new BMap.Marker(point, {
            icon : new BMap.Icon("http://www.mingyitech.cn/mingyi/images/wifi.png", new BMap.Size(36, 36), {
                                 anchor:new BMap.Size(18, 36),
                infoWindowAnchor : new BMap.Size(10, 0)
            })
        });
    else
        marker = new BMap.Marker(point, {
            icon : new BMap.Icon("http://www.mingyitech.cn/mingyi/images/lbs.png", new BMap.Size(36, 36), {
                                 anchor:new BMap.Size(18, 36),
                infoWindowAnchor : new BMap.Size(10, 0)
            })
        });
    

    map3.addOverlay(marker);
    console.log("localStorage_GPS-mark:"+marker.getPosition().lng+","+marker.getPosition().lat);
//    map3.panTo(point);
    Device.isOnline = devices_bat;
    //设备是否在线
    createWindow(devices_addr, devices_lng, devices_lat, devices_created, devices_bat);
    console.log(devices_created);
    marker.addEventListener("click", function() {
     if (infoWindow) {
                    infoWindow.close();
                }
     console.log("createWindow2");
     
     createWindow(devices_addr, devices_lng, devices_lat, devices_created, devices_bat);
        this.openInfoWindow(infoWindow);
    });
    setTimeout(function(){marker.openInfoWindow(infoWindow)},100);

window.map = map3;
    }
}

function localStorage_devicelist(deviceList,devices){
	/*localStorage.setItem("devices", devices);*/
	//$("#deviceList").html(html);
	// $(deviceList).html("");
	 $(deviceList).empty();
	var html = "";
	var device="";
	deviceSelfLength =0;
	console.log(devices.length);
	device=devices.split(",");
	/* device=localStorage.getItem(devices);*/
	for (var i = 0; i < device.length-1; i++) {
	var	device1=localStorage.getItem(device[i])
		var device_imei=device1.split(",")[0];
		var device_name=device1.split(",")[1];
		var device_phone=device1.split(",")[2];
		var device_bat=device1.split(",")[3];
		var device_lng=device1.split(",")[4];
		var device_lat=device1.split(",")[5];
		var device_addr=device1.split(",")[6];
		var device_model=device1.split(",")[7];
		var device_self=device1.split(",")[8];
		var device_rfid=device1.split(",")[9];
		var device_created=device1.split(",")[10];
		var device_password=device1.split(",")[11];
		
		device_Result= devicelist_html(html,deviceSelfLength,device_bat,device_imei,device_name,device_created,device_addr,device_self,device_password,device_name,device_phone,device_rfid,device_model);
	    html=device_Result.html;
	    deviceSelfLength=device_Result.deviceSelfLength;
	}
	$(deviceList).html(html);
	
	return $(deviceList).html(html);
}


var device_Result=null;

function devicelist_html(html,deviceSelfLength,device_bat,device_imei,device_name,device_created,device_addr,device_self,device_password,device_phone,device_rfid,device_model){
	var bat;
	if (device_bat == 0)
		bat = "off";
	else if (device_bat > 0 && device_bat <= 30)
		bat = "low";
	else if (device_bat > 30 && device_bat <= 70)
		bat = "med";
	else
		bat = "full";
		
		html += "<li class='swipe-reveal'>";
		html += "	<div class='swipe-content' style='color: #666;' onclick='javascript: selectDevice(\"" + device_imei + "\");'>";
		html += "		<a href='#' style='color: #0088d1; display: block; margin-bottom: 10px;'>";
		html += "			<b>" + device_name + "</b>";
		html += "       </a>";
		html += "       ID：" + device_imei + "<br />";
	var imeiF1=device_imei.substring(0, 1);
						/*console.log("imei_I:"+i+">>>>"+imeiF1);*/
	if(imeiF1 =="X"||imeiF1 =="Y"||imeiF1 =="Z"||imeiF1 =="x"||imeiF1 =="y"||imeiF1 =="z"){
		deviceSelfLength ++;
		html += "  <div style= '    position: relative;float: right;margin-top: -20px;margin-right: 10px;'>点击进入 &gt;&gt;</div>      ";
		html += "	</div>";
	}else{
		html += "       <span style='margin: 10px 0px -10px 0px;height:14px;display:block;'>" + (device_created ? "时间：" +device_created: "") + "</span><br /><span style='width:70%;height:65px;overflow:hidden;display: block;'>" + (device_addr == "暂无上报位置信息" ? "暂无上报位置信息" : "地址：" + device_addr) + "</span>";
		html += "  <div style= '    position: relative;float: right;margin-top: -60px;margin-right: 10px;'>左滑设置 &lt;&lt;<br/> 点击进入 &gt;&gt;</div>      ";
		html += "		<div class='battery " + bat + "' style='margin-top: -100px;margin-right: 40px;' ></div>";
		//html += "		<div class='chevron'></div>";
		html += "	</div>";

if (device_self){
	deviceSelfLength ++;
		html += "	<div class='swipe-hidden' id='device_swipe1' >";
		html += "		<a class='button' href=\"javascript: loadUpdateInfo('" + device_imei + "','" + device_password + "','" + device_name + "','" + device_phone + "','" + device_rfid + "');\">修改<br />资料</a>";
	var model = device_model;
	//增加亲情号码验证
	var familyNumber = model.length >= 2 ? parseInt(model.substring(0, 2)) : 0;
	if (familyNumber != 0) {
		html += "		<a class='button' id='FamilyNumber' href=\"javascript: loadGuardian('" + device_imei + "');\">亲情<br />号码</a>";
	}
	//增加白名单验证（G1630）
	var whiteList = model.length >= 13 ? parseInt(model.substring(11, 13)) : 0;
	if (whiteList != 0) {
		html += "		<a class='button' id='WhiteList' href=\"javascript: loadWhite('" + device_imei + "');\">白<br />名单</a>";
	}
	//html += "		<a class='button' href=\"javascript: loadUpdatePwd('" + device.imei + "');\">修改<br />密码</a>";
		html += "		<a class='button archive' href=\"javascript: removeDevice('" + device_imei + "','" + device_password + "');\">删除</a>";
		html += "	</div>";
}
	}
		html += "</li>";
		 device_Result={
				'html':html,
				'deviceSelfLength':deviceSelfLength
				};	
		
return device_Result;	
}


//账户自身终端数量
var deviceLength=0;
var chkStateHandler;
// 终端管理回调
function bandCallback(data) {
	if (data.success) {
		if (data.type == 1) {
			//Device.uBandTerminalCallback();
			stoper();
			uBandTerminal_flag = false;
			//popuo("绑定终端操作成功");
			$.afui.loadContent("#main", false, false, "none");
		} else if (data.type == 2) {
			//Device.uBandTerminalCallback();
			stoper();
			popuo("终端资料修改成功");
			uBandTerminal_flag = false;
			$.afui.goBack();
			$("#main").trigger('panelbeforeload');
		} else if (data.type == 3) {
			//Device.uBandTerminalCallback();
			stoper();
			uBandTerminal_flag = false;
			popuo("终端密码修改成功");
			$.afui.goBack();
		} else if (data.type == 4) {
			//Device.uBandTerminalCallback();
			stoper();
			popuo("删除终端操作成功");
			uBandTerminal_flag = false;
			$("#main").trigger('panelbeforeload');
		} else if (data.type == 5) {
			if (data.terminalinfo.length == 0) {
				$("#uBandTerminal_comm_id").hide();
				uBandTerminal_flag = false;
				//Device.uBandTerminalCallback();
				stoper();
				$("#deviceList").html("<div style='margin: 30px;'>暂无绑定终端<br /><br />可点击右上角“+”添加终端信息</div>");
			} else {
			 	if(isConnected){
								$("#uBandTerminal_comm_id").hide();
								//Device.uBandTerminalCallback();
								stoper();
								var html = "";
								var devices = "";
								deviceSelfLength =0;
								for (var i = 0; i < data.terminalinfo.length; i++) {
									console.log(data.terminalinfo.length);
									var device = data.terminalinfo[i];
									devices += device.imei + ",";
									// 将终端信息加到本地缓存(终端名称_自定义，终端号码_终端手机号码，IMEI_终端，密码)
									//1_IMEI,2_终端名字，3_终端号码，4_电量，5_经度，6_纬度，7_地址，8_型号值，9_self,10_rfid编号
									//bat,lng,lat,model,self,rfid(电量，经度，纬度，型号值，??,rfid编号);self不清楚
									//console.log(device.imei+":"+device.imei + "," + device.name + "," + device.phone + "," + device.bat + "," + device.lng + "," + device.lat + "," + device.addr + "," + device.model + "," + device.self + "," + device.rfid)
									var device_created=device.created ? device.created.substring(0, 4) + "-" + device.created.substring(4, 6) + "-" + device.created.substring(6, 8) + " " + device.created.substring(8, 10) + ":" + device.created.substring(10, 12) + ":" + device.created.substring(12, 14) : "";
									
									//localStorage.setItem(device.imei,device.imei + "," + device.name + "," + device.phone + "," + device.bat + "," + device.lng + "," + device.lat + "," + device.addr + "," + device.model + "," + device.self + "," + device.rfid+","+device_created);
									localStorage.setItem(device.imei,device.imei + "," + device.name + "," + device.phone + "," + device.bat + "," + device.lng + "," + device.lat + "," + device.addr + "," + device.model + "," + device.self + "," + device.rfid+","+device_created+","+device.password+","+device.loctype);

									// 缓存终端信息
									Device.setDiviceByImei(device.imei,device);

									/*var bat;
									if (device.bat == 0)
										bat = "off";
									else if (device.bat > 0 && device.bat <= 30)
										bat = "low";
									else if (device.bat > 30 && device.bat <= 70)
										bat = "med";
									else
										bat = "full";
									html += "<li class='swipe-reveal'>";
									html += "	<div class='swipe-content' style='color: #666;' onclick='javascript: selectDevice(\"" + device.imei + "\");'>";
									html += "		<a href='#' style='color: #0088d1; display: block; margin-bottom: 10px;'>";
									html += "			<b>" + device.name + "</b>";
									html += "       </a>";
									html += "       ID：" + device.imei + "<br />";
									var imeiF1=device.imei.substring(0, 1);
														console.log("imei_I:"+i+">>>>"+imeiF1);
									if(imeiF1 =="X"||imeiF1 =="Y"||imeiF1 =="Z"||imeiF1 =="x"||imeiF1 =="y"||imeiF1 =="z"){
										deviceSelfLength ++;
										html += "  <div style= '    position: relative;float: right;margin-top: -20px;margin-right: 10px;'>点击进入 &gt;&gt;</div>      ";
										html += "	</div>";
									}else{
									html += "       <span style='margin: 10px 0px -10px 0px;height:14px;display:block;'>" + (device.created ? "时间：" + (device.created.substring(0, 4) + "-" + device.created.substring(4, 6) + "-" + device.created.substring(6, 8) + " " + device.created.substring(8, 10) + ":" + device.created.substring(10, 12) + ":" + device.created.substring(12, 14)) : "") + "</span><br /><span style='width:70%;height:65px;overflow:hidden;display: block;'>" + (device.addr == "暂无上报位置信息" ? "暂无上报位置信息" : "地址：" + device.addr) + "</span>";
									html += "  <div style= '    position: relative;float: right;margin-top: -60px;margin-right: 10px;'>左滑设置 &lt;&lt;<br/> 点击进入 &gt;&gt;</div>      ";
									html += "		<div class='battery " + bat + "' style='margin-top: -100px;margin-right: 40px;' ></div>";
									//html += "		<div class='chevron'></div>";
									html += "	</div>";

								if (device.self){
									deviceSelfLength ++;
									html += "	<div class='swipe-hidden' id='device_swipe1' >";
									html += "		<a class='button' href=\"javascript: loadUpdateInfo('" + device.imei + "','" + device.password + "','" + device.name + "','" + device.phone + "','" + device.rfid + "');\">修改<br />资料</a>";
									var model = device.model;
									//增加亲情号码验证
									var familyNumber = model.length >= 2 ? parseInt(model.substring(0, 2)) : 0;
									if (familyNumber != 0) {
										html += "		<a class='button' id='FamilyNumber' href=\"javascript: loadGuardian('" + device.imei + "');\">亲情<br />号码</a>";
									}
									//增加白名单验证（G1630）
									var whiteList = model.length >= 13 ? parseInt(model.substring(11, 13)) : 0;
									if (whiteList != 0) {
										html += "		<a class='button' id='WhiteList' href=\"javascript: loadWhite('" + device.imei + "');\">白<br />名单</a>";
									}
									//html += "		<a class='button' href=\"javascript: loadUpdatePwd('" + device.imei + "');\">修改<br />密码</a>";
									html += "		<a class='button archive' href=\"javascript: removeDevice('" + device.imei + "','" + device.password + "');\">删除</a>";
									html += "	</div>";
								}
									}
									html += "</li>";*/
									
									device_Result= devicelist_html(html,deviceSelfLength,device.bat,device.imei,device.name,device_created,device.addr,device.self,device.password,device.phone,device.rfid,device.model);
								    html=device_Result.html;
								    deviceSelfLength=device_Result.deviceSelfLength;
								}

								//拿值
								deviceLength=deviceSelfLength;
								console.log("deviceLength:"+deviceLength);
								$("#deviceList").html(html);
								// 将所有终端信息加到本地缓存
								localStorage.setItem("devices", devices);
								// 设置定位界面按钮状态检查定时器
								//if (chkStateHandler == undefined)
								//	chkStateHandler = setInterval("checkState()", 100);
				 }else{
						if($("#deviceList").text().length != 0){
						console.log("没网里面不为空："+$("#deviceList").text().length );
                        						 //Device.uBandTerminalCallback();
                        						 stoper();
                                         		 $("#uBandTerminal_comm_id").hide();
                        }else{
                        console.log("没网里面为空："+$("#deviceList").text());
                                         		// Device.uBandTerminalCallback();
                                         		// $("#uBandTerminal_comm_id").show();
                                         		$("#uBandTerminal_comm_id").hide();
                                         		 if(!uBandTerminal_flag){               		
							   sendCmd({
									c : "uBandTerminal",
									id : localStorage.getItem("loginUser").split(",")[0],
									type : 5
								});
							   uBandTerminal_flag = true;	   		
						 Device.showMask_blockUI();
						 overTimeCallback_time_2("deviceList","uBandTerminal_comm_id",10000);
                                         		   }
                        }
	             }
			 	uBandTerminal_flag = false;
			}
		}
	} else {
		if (data.error == 1){
		//Device.uBandTerminalCallback();
		stoper();
		popuo("非法请求，当前用户不存在");
		uBandTerminal_flag = false;
		}
		else if (data.error == 2){
		//Device.uBandTerminalCallback();
		stoper();
		popuo("IMEI号不存在");
		uBandTerminal_flag = false;
		}
		else if (data.error == 3){
		//Device.uBandTerminalCallback();
		stoper();
		popuo("终端密码不正确");
		uBandTerminal_flag = false;
		}
		else if (data.error == 4){
		//Device.uBandTerminalCallback();
		stoper();
		popuo("终端已被绑定");
		uBandTerminal_flag = false;
		}
		else if (data.error == 5){
		//Device.uBandTerminalCallback();
		stoper();
		popuo("RFID号已被绑定");
		uBandTerminal_flag = false;
		}
		else if (data.error == 6){
		//Device.uBandTerminalCallback();
		stoper();
		popuo("非法请求，操作类型错误");
		uBandTerminal_flag = false;
		}
		else if (data.error == 7){
		//Device.uBandTerminalCallback();
		stoper();
		popuo("终端已满");
		uBandTerminal_flag = false;
        }else{
        	uBandTerminal_flag = false;
        	//拿到所有终端
        	
        	if($("#deviceList").text().length != 0){
				console.log("没网里面不为空："+$("#deviceList").text().length );
                						 //Device.uBandTerminalCallback();
                						 stoper();
                                 		 $("#uBandTerminal_comm_id").hide();
                }else{
                console.log("没网里面为空："+$("#deviceList").text());
                                 		// Device.uBandTerminalCallback();
                                 		// $("#uBandTerminal_comm_id").show();
                                 		$("#uBandTerminal_comm_id").hide();
                                 		 if(!uBandTerminal_flag){               		
					   sendCmd({
							c : "uBandTerminal",
							id : localStorage.getItem("loginUser").split(",")[0],
							type : 5
						});
					   uBandTerminal_flag = true;	   		
				 Device.showMask_blockUI();
				 overTimeCallback_time_2("deviceList","uBandTerminal_comm_id",10000);
                  }

                }
        
        }
	}
	if (data.type == 1) {
		$("#bandBtn").attr("href", "javascript: bandDevice();");
		$("#bandBtn").attr("class", "button block blue");
	} else if (data.type == 2) {
		$("#updateInfoBtn").attr("href", "javascript: updateInfo();");
		$("#updateInfoBtn").attr("class", "button block blue");
	} else if (data.type == 3) {
		$("#updatePwdBtn").attr("href", "javascript: updatePassword();");
		$("#updatePwdBtn").attr("class", "button block blue");
	}
}

// 绑定终端
function validateDevice() {
	if ($("#device-name").val().trim() == "") {
		popuo("终端名称不能为空");
		return false;
	} else if ($("#device-phone").val().trim() == "") {
		popuo("终端号码不能为空");
		return false;
	} else if (!/^(?![,;])[*#+,;0-9]{2,20}$/.test($("#device-phone").val().trim())) {
		popuo("终端号码格式不正确");
		return false;
	} else if ($("#device-imei").val().trim() == "") {
		popuo("IMEI号不能为空");
		return false;
	} else if ($("#device-password").val().trim() == "") {
		popuo("密码不能为空");
		return false;
	}
	return true;
}

function bandDevice() {
	if (validateDevice()) {
		if(isConnected){
						$("#bandBtn").attr("href", "javascript: void(0);");
        				$("#bandBtn").attr("class", "button block gray");
                       	sendCmd({
                        			c : "uBandTerminal",
                        			id : localStorage.getItem("loginUser").split(",")[0],
                        			name : $("#device-name").val().trim(),
                        			phone : $("#device-phone").val().trim(),
                        			imei : $("#device-imei").val().trim(),
                        			password : $("#device-password").val().trim(),
                        			type : 1
                        		});
                       	 Device.showMask_blockUI_2();
                       	// Device.uBandTerminalCallback_10();
                       	overTimeCallback_time("bandBtn","bandDevice",10000);
	   	}else{
			popuo("连接超时，请检查网络设置");
			socket.connect();
		}

	}
}

// 删除终端
function removeDevice(imei, password) {
	function removeD(imei){
		if(isConnected){
                   	sendCmd({
                    			c : "uBandTerminal",
                    			id : localStorage.getItem("loginUser").split(",")[0],
                    			imei : imei,
                    			password : password,
                    			type : 4
                    		});
                   	 Device.showMask_blockUI_3();
                   	// Device.uBandTerminalCallback_10();
                   	setTimeout_showMask(unblockUI,10000);
		}else{
			popuo("连接超时，请检查网络设置");
			socket.connect();
		}
	}
	 deletePopuo("删除终端",imei,removeD);
}

// 亲情号码
function loadGuardian(imei) {
	$("#guardian-imei").val(imei);
	$.afui.loadContent("#guardian", false, false, "none");
}

function guardian() {
	var model = localStorage.getItem($("#guardian-imei").val()).split(",")[7];
	var guardianCount = model.length >= 2 ? model.substring(0, 2) : 0;
	var flag = true;
	for (var i = 0; i < guardianCount; i++) {
		if ($("#mobile" + (i + 1)).val().trim() != "" && !/^(?![,;])[*#+,;0-9]{2,20}$/.test($("#mobile" + (i + 1)).val().trim())) {
			popuo("亲情号码" + (i + 1) + "格式不正确");
			flag = false;
			break;
		}
	}
	if (flag) {
		if(isConnected){
                   	 var data = {
                     			c : "uRelateNumber",
                     			imei : $("#guardian-imei").val(),
                     			type : 2
                     		};
                     		for (var i = 0; i < guardianCount; i++)
                     			data["mobile" + (i + 1)] = $("#mobile" + (i + 1)).val().trim();
                     		sendCmd(data);
                   	 Device.showMask_blockUI_2();
                   	// Device.uBandTerminalCallback_10();
                   	setTimeout_showMask(unblockUI,10000);

        }else{
             popuo("连接超时，请检查网络设置");
             socket.connect();
         }
	}
}

// 白名单
function loadWhite(imei) {
	$("#white-imei").val(imei);
	$.afui.loadContent("#white", false, false, "none");
}

function white() {
	var model = localStorage.getItem($("#white-imei").val()).split(",")[7];
	var whiteCount = model.length >= 13 ? model.substring(11, 13) : 0;
	var flag = true;
	for (var i = 0; i < whiteCount; i++) {
		if ($("#white-" + (i + 1)).val().trim() != "" && !/^(?![,;])[*#+,;0-9]{2,20}$/.test($("#white-" + (i + 1)).val().trim())) {
			popuo("白名单" + (i + 1) + "格式不正确");
			flag = false;
			break;
		}
	}
	if (flag) {
	   if(isConnected){
                   	 var data = {
                     			c : "uRelateNumber",
                     			imei : $("#white-imei").val(),
                     			type : 4
                     		};
                     		for (var i = 0; i < whiteCount; i++)
                     			data["mobile" + (i + 1)] = $("#white-" + (i + 1)).val().trim();
                     		sendCmd(data);
                   	 Device.showMask_blockUI_2();
                   	// Device.uBandTerminalCallback_10();
                   	setTimeout_showMask(unblockUI,10000);
       }else{
          popuo("连接超时，请检查网络设置");
          socket.connect();
       }
	}
}

//亲情号码设置
function uRelateNumberCallback(data) {
	if (data.success) {
		if (data.type == 1) {
			//Device.uBandTerminalCallback();
			stoper();
			var model = localStorage.getItem($("#guardian-imei").val()).split(",")[7];
			var guardianCount = model.length >= 2 ? model.substring(0, 2) : 0;
			$("#guardianContent").html("");
			for (var i = 0; i < guardianCount; i++) {
				var html = "<label for='mobile" + (i + 1) + "'>号码" + (i + 1) + "</label>";
				html += "<input id='mobile" + (i + 1) + "' value='" + data["mobile" + (i + 1)] + "' type='tel' placeholder='请输入亲情号码' maxlength='20' />";
				$("#guardianContent").html($("#guardianContent").html() + html);
			}
		} else if (data.type == 2) {
			//Device.uBandTerminalCallback();
			stoper();
			popuo("亲情号码保存成功");
			$.afui.goBack();
            $("#main").trigger('panelbeforeload');
		} else if (data.type == 3) {
			//Device.uBandTerminalCallback();
			stoper();
			var model = localStorage.getItem($("#white-imei").val()).split(",")[7];
			var whiteCount = model.length >= 13 ? model.substring(11, 13) : 0;
			$("#whiteContent").html("");
			for (var i = 0; i < whiteCount; i++) {
				var html = "<label for='white-" + (i + 1) + "'>白名单" + (i + 1) + "</label>";
				html += "<input id='white-" + (i + 1) + "' value='" + data["mobile" + (i + 1)] + "' type='tel' placeholder='请输入白名单' maxlength='20' />";
				$("#whiteContent").html($("#whiteContent").html() + html);
			}
		} else{
		//Device.uBandTerminalCallback();
		stoper();
		popuo("白名单保存成功");
		$.afui.goBack();
        $("#main").trigger('panelbeforeload');
		}
	} else {
		//Device.uBandTerminalCallback();
		stoper();
		popuo("IMEI号不存在");
	}
}

// 修改终端资料
function loadUpdateInfo(imei, password, name, phone, rfid) {
	$("#updateInfo-imei").val(imei);
	$("#updateInfo-pwd").val(password);
	$("#updateInfo-name").val(name);
	$("#updateInfo-phone").val(phone);
	$("#updateInfo-rfid").val(rfid);
	$.afui.loadContent("#updateInfo", false, false, "none");
}

function updateInfo() {
	if ($("#updateInfo-name").val().trim() == "")
		popuo("终端名称不能为空");
	else if ($("#updateInfo-phone").val().trim() == "")
		popuo("终端号码不能为空");
	else if (!/^(?![,;])[*#+,;0-9]{2,20}$/.test($("#updateInfo-phone").val().trim()))
		popuo("终端号码格式不正确");
	else {
		 if(isConnected){
						 $("#updateInfoBtn").attr("href", "javascript: void(0);");
         				 $("#updateInfoBtn").attr("class", "button block gray");
                       	 sendCmd({
                         			c : "uBandTerminal",
                         			imei : $("#updateInfo-imei").val().trim(),
                         			name : $("#updateInfo-name").val().trim(),
                         			rfid : $("#updateInfo-rfid").val().trim(),
                         			phone : $("#updateInfo-phone").val().trim(),
                         			password : $("#updateInfo-pwd").val().trim(),
                         			id : localStorage.getItem("loginUser").split(",")[0],
                         			type : 2
                         		});
                       	 Device.showMask_blockUI_2();
                       //	 Device.uBandTerminalCallback_10();
                       overTimeCallback_time("updateInfoBtn","updateInfo",10000);
         }else{
				popuo("连接超时，请检查网络设置");
				socket.connect();
		 }
	}
}

// 修改终端密码
function loadUpdatePwd(imei) {
	$("#device-imei").val(imei);
	$.afui.loadContent("#updatePwd", false, false, "none");
}

function updatePassword() {
	if ($("#device-oldPassword").val().trim() == "")
		popuo("原密码不能为空");
	else if ($("#device-newPassword").val().trim() == "")
		popuo("新密码不能为空");
	else if ($("#device-newPassword").val().trim().length < 4)
		popuo("新密码长度不能小于4位");
	else if ($("#device-newPassword").val().trim() != $("#device-rePassword").val().trim())
		popuo("两次输入的密码不一致");
	else {
		$("#updatePwdBtn").attr("href", "javascript: void(0);");
		$("#updatePwdBtn").attr("class", "button block gray");
		sendCmd({
			c : "uBandTerminal",
			imei : $("#device-imei").val().trim(),
			oldPassword : $("#device-oldPassword").val().trim(),
			newPassword : $("#device-newPassword").val().trim(),
			id : localStorage.getItem("loginUser").split(",")[0],
			type : 3
		});
	}
}

// 修改密码
function uChangePasswordCallback(data) {
	if (data.success) {
		//Device.uBandTerminalCallback();
		stoper();
		popuo("密码已修改，请使用新密码登录系统");
		$("#modifyPassword").removeClass('active');
		logout();
	} else {
		if (data.error == 1){
		//Device.uBandTerminalCallback();
		stoper();
		popuo("非法请求，请重试");
		}
		else if (data.error == 2){
		//Device.uBandTerminalCallback();
		stoper();
		popuo("原密码不正确");
		}

	}
	$("#modifyPwdBtn").attr("href", "javascript: modifyPassword();");
	$("#modifyPwdBtn").attr("class", "button block blue");
}

function modifyPassword() {
	if ($("#modify-oldPassword").val().trim() == "")
		popuo("原密码不能为空");
	else if ($("#modify-newPassword").val().trim() == "")
		popuo("新密码不能为空");
	else if ($("#modify-newPassword").val().trim().length < 6)
		popuo("新密码长度不能小于6位");
	else if ($("#modify-newPassword").val().trim() != $("#modify-rePassword").val().trim())
		popuo("两次输入的密码不一致");
	else {

		 if(isConnected){
		 				$("#modifyPwdBtn").attr("href", "javascript: void(0);");
         				$("#modifyPwdBtn").attr("class", "button block gray");
                       	sendCmd({
                        			c : "uChangePassword",
                        			oldPassword : $("#modify-oldPassword").val(),
                        			newPassword : $("#modify-newPassword").val(),
                        			id : localStorage.getItem("loginUser").split(",")[0]
                        		});
                       	 Device.showMask_blockUI_2();
                       	// Device.uBandTerminalCallback_10();
                       	overTimeCallback_time("modifyPwdBtn","modifyPassword",10000);
         }else{
               popuo("连接超时，请检查网络设置");
               socket.connect();
         }
	}
}

// 设置用户资料
function setting() {
	$("#settingBtn").attr("href", "javascript: void(0);");
	$("#settingBtn").attr("class", "button block gray");
	var datas = "";
	datas += $("#setting-notice").prop("checked") + ",-,";
	datas += $("#setting-sound").prop("checked") + ",-,";
	datas += $("#setting-vibrate").prop("checked") + ",-,";
	datas += $("#logoImg").attr("src") + ",-,";
	datas += $("#setting-name").val() + ",-,";
	datas += $("#setting-sex").val();
	localStorage.setItem(localStorage.getItem("loginUser").split(",")[0], datas);
	$("#logoImg-menu").attr("src", $("#logoImg").attr("src"));
	$("#name-menu").html($("#setting-name").val());
	popuo("保存设置操作成功");
	$("#settingBtn").attr("href", "javascript:setting();");
	$("#settingBtn").attr("class", "button block blue");
}

// 家庭成员
function uRelationCallback(data) {
	if (data.success) {
		if (data.type == 1) {
			//Device.uBandTerminalCallback();
			stoper();
			var html = "";
			for (var i = 0; i < data.relations.length; i++) {
				var relation = data.relations[i];
				html += "<li class='swipe-reveal'>";
				html += "	<div class='swipe-content'>";
				html += "		<a href='#' style='color: #666;'>";
				html += "			<b>" + relation.name + "</b><br /> <br />" + relation.mobile;
				html += "       </a>";
				html += "	</div>";
				html += "	<div class='swipe-hidden'>";
				if (relation.enable)
					html += "		<a class='button2 archive' href=\"javascript: removeRelation('" + relation.id + "');\">删除</a>";
				html += "	</div>";
				html += "</li>";
			}
			$("#relationList").html(html);
			/* 如果非管理员，不做邀请限制
			if (data.admin)
				$("#inviteBtn").css("display", "block");
			else
				$("#inviteBtn").css("display", "none");*/
		} else if (data.type == 2) {
			//Device.uBandTerminalCallback();
			stoper();
			//popuo("邀请家庭成员操作成功");
			$("#family-name").val("");
			$("#family-mobile").val("");
			$.afui.goBack();
			// 加载家庭成员
			sendCmd({
				c : "uRelation",
				id : localStorage.getItem("loginUser").split(",")[0],
				type : 1
			});
		} else {
			//Device.uBandTerminalCallback();
			stoper();
			popuo("删除家庭成员操作成功");
			// 加载家庭成员
			sendCmd({
				c : "uRelation",
				id : localStorage.getItem("loginUser").split(",")[0],
				type : 1
			});
		}
	} else {
		if (data.error == 1){
			//Device.uBandTerminalCallback();
			stoper();
			popuo("系统错误，用户不存在");
		}
		else{
			//Device.uBandTerminalCallback();
			stoper();
			popuo("成员电话号码已存在");
		}

	}
}

function addRelation() {
	if ($("#family-name").val().trim() == "")
		popuo("成员名称不能为空");
	else if ($("#family-mobile").val().trim() == "")
		popuo("成员电话号码不能为空");
	else if (!/^(?![,;])[*#+,;0-9]{2,20}$/.test($("#family-mobile").val().trim()))
		popuo("成员电话号码格式不正确");
	else {
	 		if(isConnected){
                  sendCmd({
                  			c : "uRelation",
                  			id : localStorage.getItem("loginUser").split(",")[0],
                  			type : 2,
                  			name : $("#family-name").val(),
                  			mobile : $("#family-mobile").val()
                  		});
                   	 Device.showMask_blockUI_2();
                   	// Device.uBandTerminalCallback_10();
                   	setTimeout_showMask(unblockUI,10000);
            }else{
                   	popuo("连接超时，请检查网络设置");
                   	socket.connect();
            }
	}
}

function removeRelation(id) {
	deletePopuo("删除家庭成员",id,removeR);
}

function removeR(id){
	  	if(isConnected){
						sendCmd({
								c : "uRelation",
								id : localStorage.getItem("loginUser").split(",")[0],
								type : 3,
								relation : id
						});
                       	 Device.showMask_blockUI_3();
                       	// Device.uBandTerminalCallback_10();
                       	setTimeout_showMask(unblockUI,10000);
        }else{
              popuo("连接超时，请检查网络设置");
              socket.connect();
        }
}


var circlesLength=0;
var locateCtrl;
// 进入终端详情
function selectDevice(imei) {
	var device = localStorage.getItem(imei);
	// 设置当前选中终端
	localStorage.setItem("device", device);
	var devices = device.split(",");
	// 设置拔号电话
	// 0_IMEI,1_终端名字，2_终端号码，3_电量，4_经度，5_纬度，6_地址，7_型号值，8_self,9_rfid编号
	// 设置拔号电话
	//如果是流量卡，则屏蔽此功能,如果不是流量卡，则开启此功能(流量卡可以根据数据词典来区分，第25位)
	var model = devices[7];
	var phonenumber=parseInt(devices[2]);
	var dialLinkCount = model.length >= 25 ? parseInt(model.substring(24, 25)) : 0;
	if (dialLinkCount == 1) {
		$("#dialLink").css("display", "none");
		$("#monitorLi").hide();
		//如果是流量卡，需要关闭
	} else {
		$("#dialLink").css("display", "block");
		//window.phoneplugin.call();
		$("#dialLink").attr("href", "javascript: self.location = 'tel://" + devices[2] + "';");
		//$("#dialLink").attr("href", "javascript: window.phoneplugin.call(phonenumber);");
		$("#monitorLi").show();
		//如果不是流量卡，打开
	}
	
    //$("#dialLink").attr("href", "javascript: window.phoneplugin.call("+phonenumber+");");
	$("#dialLink").attr("href", "javascript: self.location = 'tel://" + devices[2] + "';");
	   //是否是单次定位还是30分跟踪
       var model = Device.getCurrentModel();
         var msgType = Device.getMsgType(model);
         var linkType = Device.getLinkType(model);

         switch (msgType + linkType) {
         // 如果是收费的短信网关，并且是短链接，点击后，要提示客户：“开启30分钟的位置上报”，开启后，30分钟内不允许再次点击
         case '00': {
         	 var start= Device.getDeviceLocTime(imei);
              if(parseInt(new Date().getTime() - start)>= 1800 * 1000){

              	Device.locationControl.data.showloading = false;
              }else{
              	Device.locationControl.data.showloading = true;
              }
             break;
         }//case '10':
         case '10':
         case '11':
         case '01': {
         		var start= Device.getDeviceLocTime(imei);
              if(parseInt(new Date().getTime() - start)>= 90 * 1000){
              	Device.locationControl.data.showloading = false;
              }else{
              	Device.locationControl.data.showloading = true;
              }
              break;
         }
         default: {
      		var start= Device.getDeviceLocTime(imei);
           if(parseInt(new Date().getTime() - start)>= 90 * 1000){
           	Device.locationControl.data.showloading = false;
           }else{
           	Device.locationControl.data.showloading = true;
           }
          break;
      }
         
     }
	
      var imeiF1=imei.substring(0, 1);
     		console.log("imei_I:"+imeiF1);
     		if(imeiF1 =="X"||imeiF1 =="Y"||imeiF1 =="Z"||imeiF1 =="x"||imeiF1 =="y"||imeiF1 =="z"){
     			// 进入定位界面
     			$.afui.loadContent("#notice", false, false, "none");
     			// 跨view跳转bug修复
     			$("#main").removeClass('active');
     			//document.getElementById("noticeLink").selected = true;
     			$("#locationLink").attr("href", "#");
     			$("#dialLink").attr("href", "#");
     			$("#settingLinkBtn").attr("href", "#");
     			//$("#notice").trigger('panelbeforeload');


     			$("#locationLink").attr("href", "javascript: popuo('需要智能学生卡配合使用');");
     			$("#dialLink").attr("href", "javascript: popuo('需要智能学生卡配合使用');");
     			$("#settingLinkBtn").attr("href", "javascript: popuo('需要智能学生卡配合使用');");


     		}else{
     			console.log("user");
     			// 进入定位界面
     			$.afui.loadContent("#location", false, false, "none");

     			// 跨view跳转bug修复
     			$("#main").removeClass('active');
     			document.getElementById("locationLink").selected = true;
     			$("#locationLink").attr("href", "#location");
     			$("#settingLinkBtn").attr("href", "#deviceSetting");
     			$("#location").trigger('panelbeforeload');
     			$("#location").trigger('panelload');
     			
				/*sendCmd({
                		c : "uGetGPS",
                		imei : devices[0]
                	});*/

     		}
/*	// 进入定位界面
	$.afui.loadContent("#location", false, false, "none");
	// 跨view跳转bug修复
	$("#main").removeClass('active');
	$("#location").trigger('panelbeforeload');
	$("#location").trigger('panelload');*/
	// 是否有管理功能终端
	if (devices[8] == 'true')
		$("#settingLinkBtn").css("display", "block");
	else
		$("#settingLinkBtn").css("display", "none");
	// 定位
	//popuo("进入终端详情IMEI："+devices[0]);
	/*sendCmd({
		c : "uGetGPS",
		imei : devices[0]
	});*/
	// 查看有无新通知消息
	
	uGetNewMessage();
	// 初始化更多功能显示
	// var model = devices[7];
	// 上课隐身
	var hiddingCount = model.length >= 11 ? parseInt(model.substring(10, 11)) : 0;
	if (hiddingCount == 0)
		$("#hiddingLi").hide();
	else
		$("#hiddingLi").show();
	//	safeArea 安全区域设置
	var safeCount = model.length >= 8 ? parseInt(model.substring(6, 8)) : 0;
	if (safeCount == 0)
		$("#safeArea").hide();
	else
		$("#safeArea").show();
	// 定时开关机
	var powerCount = model.length >= 16 ? model.substring(14, 16) : '00';
	if (powerCount == '00')
		$("#powerLi").hide();
	else
		$("#powerLi").show();
	// 闹钟
	var clockCount = model.length >= 18 ? parseInt(model.substring(16, 18)) : 0;
	if (clockCount == 0)
		$("#clockLi").hide();
	else
		$("#clockLi").show();
	// 监听
	   var monitorCount = model.length >= 22 ? parseInt(model.substring(21, 22)) : 0;
	   if(monitorCount == 0)
	      $("#monitorLi").hide();
	    else
	       $("#monitorLi").show();
	// 定时跟踪
	var followCount = model.length >= 23 ? parseInt(model.substring(22, 23)) : 0;
	if (followCount == 0)
		$("#followLi").hide();
	else
		$("#followLi").show();
	//围栏数
	circlesLength =model.length >= 8 ?parseInt(model.substring(6, 8)): 0 ;
	console.log("circlesLength:"+circlesLength);
	// 考勤记录
	if (devices[9] == "")
		$("#attdanceLi").hide();
	else
		$("#attdanceLi").show();
	// 是否长连接  19位：表示是短连接还是长链接，0短连接   1长连接
	var longpoll = model.length >= 19 ? parseInt(model.substring(18, 19)) : 0;
	if (longpoll == 0) {
		$("#hiddingChoose").css("display", "none");
		 $("#followingContent").css("display", "none");
		$("#hidding-more").css("display", "none");
		$("#alarm_all").css("display", "none");
		$("#hid_all").css("display", "none");
		$("#hidding-alarm-more").css("display", "none");
		$("#hidding-alarm-more2").css("display", "none");
		$("#hidding-alarm-more3").css("display", "none");
	} else {
		$("#hiddingChoose").css("display", "block");
		$("#followingContent").css("display", "block");
		$("#hidding-more").css("display", "block");
		//闹钟
		$("#alarm_all").css("display", "block");
		//上课隐身
		$("#hid_all").css("display", "block");
		$("#hidding-alarm-more").css("display", "block");
		$("#hidding-alarm-more2").css("display", "block");
		$("#hidding-alarm-more3").css("display", "block");
	}
	//div_loc_showloading(imei);

}